<?php
/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided data can identity the user.
 * 
 * Bocheng Chen, 10.07.2012
 * 
 * LBB Solutions Oy 版权所有 @ 2012
 */
class UserIdentity extends CUserIdentity
{
	// Need to store the user's ID:
	private $_id;
	public function getId() {
		return $this->_id;
	}
	public function setId($id) {
		$this->_id = $id;
	}
	
	private $_type = null;
	public function setType($type) {
		$this->_type = $type;
	}
	
	/**
	 * Authenticates a user.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		if (null === $this->_type) {
			throw new Exception('The user type cannot be empty.');
		}
		
		$sql_user = 'SELECT password, id, email, mobile, picture, name, first_name, last_name, gender, location, lang, time_zone, status FROM tbl_user_account ';
		if (2 === $this->_type) {
			$sql_user .= ' WHERE mobile=:user';
		} elseif (1 === $this->_type) {
			$sql_user .= ' WHERE email=:user';
		} else {
			$sql_user .= ' WHERE id=:user';
		}
		$sql_user .= ' LIMIT 1';
		// fetch password and username
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_user);
		$row = $command->queryRow(true, array(':user' => $this->username));
		$connection->active = false;
		
		// check the password with md5
		if (empty($row)) {
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		} else {
			//first md5, then hash32.
			$pasword_in_db = BUtils::Hash32(md5($this->password));
			if ($row['password'] === $pasword_in_db) {
				$this->_id = $row['id'];
				$this->setState('email', $row['email']);
				$this->setState('mobile', $row['mobile']);
				$this->setState('status', $row['status']);
				$this->setState('name', $row['name']);
				$this->setState('first_name', $row['first_name']);
				$this->setState('last_name', $row['last_name']);
				$this->setState('gender', $row['gender']);
				$this->setState('picture', $row['picture']);
				$this->setState('location', $row['location']);
				$this->setState('lang', $row['lang']);
				$this->setState('time_zone', $row['time_zone']);
				//TODO: just test for Facebook login
				$this->setState('facebook', 1);
				//set the language according to $row['lang']
				if (!empty($row['lang'])) {
					BUtils::SetLanguage($row['lang']);
				}
				$this->errorCode = self::ERROR_NONE;
			} else {
				$this->errorCode = self::ERROR_PASSWORD_INVALID;
			}
		}
		return (!$this->errorCode);
	}
	
	/**
	 * Create an account with email and password.
	 * @return boolean 
	 */
	public function createAccount() {
		//first md5, then hash32.
		$pasword_in_db = BUtils::Hash32(md5($this->password));
		
		// save md5(password) and username
		try {
			$connection = Yii::app()->db;
			$sql_user = 'INSERT INTO tbl_user_account ({user}, password) VALUES (:user, :password)';
			$sql_query = 'SELECT id FROM tbl_user_account WHERE {user}=:user AND password=:password';
			if (2 === $this->_type) {
				$this->username = CustomerHelper::formatMobile($this->username);//use the standard mobile number format
				$this->setState('mobile', $this->username);
				$sql_user = str_replace('{user}', 'mobile', $sql_user);
				$sql_query = str_replace('{user}', 'mobile', $sql_query);
			} else {
				$this->setState('email', $this->username);
				$sql_user = str_replace('{user}', 'email', $sql_user);
				$sql_query = str_replace('{user}', 'email', $sql_query);
			}
			$command = $connection->createCommand($sql_user);
			$command->execute(array(':user'=>$this->username, ':password'=>$pasword_in_db));

			$command = $connection->createCommand($sql_query);
			$id_user = $command->queryScalar(array(':user'=>$this->username, ':password'=>$pasword_in_db));
			$connection->active = false;
			
			$this->errorCode = self::ERROR_NONE;
			
			if (!empty($id_user)) $this->_id = $id_user;
			$this->setState('status', 0);
		} catch (Exception $ex) {
			Yii::log("ERROR : createAccount : \n"
				. $ex->getMessage() . "\n"
				. $ex->getTraceAsString(), CLogger::LEVEL_ERROR);
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		}

		return (!$this->errorCode);
	}
	
	/**
	 * Register an account with email/mobile and password.
	 * @return boolean 
	 */
	public function registerAccount($id_user) {
		//first md5, then hash32.
		$pasword_in_db = BUtils::Hash32(md5($this->password));
		
		try {
			$connection = Yii::app()->db;
			$sql_user = 'UPDATE tbl_user_account SET password=:password WHERE id=:id';
			$command = $connection->createCommand($sql_user);
			$command->execute(array(':id'=>$id_user, ':password'=>$pasword_in_db));
			$connection->active = false;
			
			if (2 === $this->_type) {
				$this->username = CustomerHelper::formatMobile($this->username);//use the standard mobile number format
				$this->setState('mobile', $this->username);
			} else {
				$this->setState('email', $this->username);
			}
			$this->_id = $id_user;
			$this->setState('status', 99);
			$this->errorCode = self::ERROR_NONE;
		} catch (Exception $ex) {
			Yii::log("ERROR : registerAccount : \n"
				. $ex->getMessage() . "\n"
				. $ex->getTraceAsString(), CLogger::LEVEL_ERROR);
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		}
		return (!$this->errorCode);
	}
}